<?php

/**
 * Created by PhpStorm.
 * User: hjc_0
 * Date: 2016/8/15
 * Time: 15:50
 */
class SessionRedis
{
    private $handle;    //redis连接句柄
    private $options;   //session配置

    public function __construct($options = null)
    {
        if (!extension_loaded('redis')) {
            throw_exception(L('_NOT_SUPPERT_') . ':redis');
        }

        $defOption = array(
            'host' => C('SESSION_REDIS_HOST') ? C('SESSION_REDIS_HOST') : '127.0.0.1',
            'port' => C('SESSION_REDIS_PORT') ? C('SESSION_REDIS_PORT') : 6379,
            'timeout' => C('SESSION_CACHE_TIMEOUT') ? C('SESSION_CACHE_TIMEOUT') : false,
            'persistent' => false,
            'passwd' => C('SESSION_REDIS_AUTH'),
            'select_db' => 0,
        );
        if (!empty($options)) {
            $options = array_merge($defOption,$options);
        } else {
            $options = $defOption;
        }

        $this->options = $options;
        $this->options['expire'] = C('SESSION_EXPIRE') ? : ini_get('session.gc_maxlifetime');
        $this->options['prefix'] =  $options['prefix'] ? : C('SESSION_PREFIX');
    }

    /**
     * 连接redis
     */
    public function connect()
    {
        $func = $this->options['persistent'] ? 'pconnect' : 'connect';
        $redis = new Redis();
        $connected = $this->options['timeout'] === false
            ? $redis->$func($this->options['host'], $this->options['port'])
            : $redis->$func($this->options['host'], $this->options['port'], $this->options['timeout']);

//        if ( !$redis->auth($this->options['passwd']) ) {
//            throw_exception(L('_REDIS_AUTH_ERROR_'));
//        }

        $this->handle = $redis;
    }

    /**
     * 打开session
     * @param string $savePath session保存路径
     * @param string $sessName session名称
     */
    public function open($savePath, $sessName)
    {
        if (is_resource($this->handle) ) {
            return true;
        }

        //连接redis
        $this->connect();
        if (!$this->handle) {
            return false;
        }
        $this->gc(null);
        return true;
    }

    /**
     * 关闭session
     */
    public function close()
    {
        if ($this->options['persistent'] == 'pconnect') {
            $this->handler->close();
        }
        return true;
    }

    /**
     * 读取session
     * @param int $sessID
     */
    public function read($sessID)
    {
        $res = $this->handle->get($this->options['prefix'].$sessID);
        return $res;
    }

    /**
     * 写到session
     * @param string $sessID    session_id
     * @param string $sessData  session数据
     */
    public function write($sessID,$sessData)
    {
        $expire = intval($this->options['expire']);
        $sessID = $this->options['prefix'].$sessID;

        if ($expire) {
            $result = $this->handle->setex($sessID,$expire,$sessData);
        } else {
            $result = $this->handle->set($sessID,$sessData);
        }

        return $result;
    }

    /**
     * 删除SESSION
     * @param string $sessID    sessionId
     */
    public function destroy($sessID)
    {
        $res = $this->handle->del($this->options['prefix'].$sessID);
        return $res;
    }

    /**
     * 垃圾回收
     * @param $sessMaxLifeTime
     */
    public function gc($sessMaxLifeTime)
    {
        return true;
    }

    /**
     * 打开session
     */
    public function execute()
    {
        session_set_save_handler(
            array($this, "open"),
            array($this, "close"),
            array($this, "read"),
            array($this, "write"),
            array($this, "destroy"),
            array($this, "gc")
        );
    }
}